#include <iostream>
#include <vector>
#include <algorithm>

// 观察者接口
class Observer{
public:
    virtual ~Observer() = default;
    virtual void update(const std::string& message) = 0;
};

// 主题接口
class Subject{
    std::vector<Observer*> observers;
public:
    void attach(Observer* observer){
        observers.push_back(observer);
    }
    void detach(Observer* observer){
        auto it = std::find(observers.begin(), observers.end(), observer);
        if(it != observers.end()) observers.erase(it);
    }
    void notify(const std::string& message){
        for(auto observer : observers){
            observer->update(message);
        }
    }
};

// 具体主题
class ConcreteSubject : public Subject{
    std::string _state;
public:
    void setState(const std::string& state){
        _state = state;
        notify(_state);
    }
    std::string getState() const{
        return _state;
    }
};

// 具体观察者
class ConcreteObserver : public Observer{
    std::string name;
public:
    ConcreteObserver(const std::string& name) : name(name) {}
    void update(const std::string& message) override{
        std::cout << name << "received message: " << message << std::endl;
    }
};

int main()
{
    ConcreteSubject subject;

    ConcreteObserver observer1("observer 1");
    ConcreteObserver observer2("observer 2");

    subject.attach(&observer1);
    subject.attach(&observer2);

    subject.setState("State 1");
    subject.setState("State 2");

    subject.detach(&observer1);

    subject.setState("State 3");

    return 0;
}